package com.breeze.components.core.util.event;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * 事件注册
 *
 * @author breeze
 */
@Component
public class ApplicationContextUtil {

  private static ApplicationContext applicationContext;

  public ApplicationContextUtil(ApplicationContext applicationContext) {
    ApplicationContextUtil.applicationContext = applicationContext;
  }

  public static void publishEvent(ApplicationEvent applicationEvent) {
    applicationContext.publishEvent(applicationEvent);
  }

  public static void afterTransactionRunner(Runnable runnable) {
    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
      runnable.run();
      return;
    }
    TransactionSynchronizationManager.registerSynchronization(
        new TransactionSynchronization() {
          @Override
          public void afterCommit() {
            runnable.run();
          }
        });
  }

  public static void publishEventAfterTransaction(ApplicationEvent applicationEvent) {
    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
      publishEvent(applicationEvent);
      return;
    }
    TransactionSynchronizationManager.registerSynchronization(
        new TransactionSynchronization() {
          @Override
          public void afterCommit() {
            publishEvent(applicationEvent);
          }
        });
  }
}
